package glen.util;

/**
 * Created by rachatanawee on 4/9/2014.
 */

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@ManagedBean(name = "loginMgb")
@RequestScoped
public class LoginMgb {
    public static final String HOME_URL = "/index.xhtml";

    private String username;
    private String password;
    private boolean remember;

    public boolean isRemember() {
        return remember;
    }

    public void setRemember(boolean remember) {
        this.remember = remember;
    }

    public String getUsername() {

        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void submit() throws IOException {
        FacesContext context = FacesContext.getCurrentInstance();
        try {
            SecurityUtils.getSubject().login(new UsernamePasswordToken(username, password, remember));

            //SavedRequest savedRequest = WebUtils.getAndClearSavedRequest((HttpServletRequest)context.getExternalContext().getRequest());
            HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
            FacesContext.getCurrentInstance().getExternalContext().redirect(HOME_URL);
            //response.sendRedirect(savedRequest != null ? savedRequest.getRequestUrl() : HOME_URL);
            //FacesContext.getCurrentInstance().getExternalContext().getResponse().(savedRequest != null ? savedRequest.getRequestUrl() : HOME_URL);
        } catch (AuthenticationException e) {
            //e.printStackTrace(); // TODO: logger.
            context.addMessage(null, new FacesMessage("Unknown user, please try again"));

        }
    }

    public void logout() throws IOException {
        SecurityUtils.getSubject().logout();

        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        FacesContext.getCurrentInstance().getExternalContext().redirect(HOME_URL);
    }

}
